<script setup lang="ts">
import {
  clearPrinter,
  createPrinter,
  deletePrinter,
  initPrinter,
  printerDetail,
  PrinterForm,
  printerList,
  PrinterQuery,
  updatePrinter,
} from "@/api/printer";

import {printerTypeOpts, statusOpts} from "@/utils/status";
import {printerFields} from "@/utils/field";
import {getSupplierOptions} from "@/api/supplier";

defineOptions({
  name: "Printer",
  inheritAttrs: false,
});

const queryFormRef = ref(ElForm);
const objFormRef = ref(ElForm);

const loading = ref(false);
const ids = ref<number[]>([]);
const total = ref(0);

const modelFields = printerFields();
const typeOptions = printerTypeOpts();
const statusOptions = statusOpts();

const queryParams = reactive<PrinterQuery>({
  pageNum: 1,
  pageSize: 10,
});

const lists = ref<PrinterQuery[]>();
const dialog = reactive({
  title: "",
  visible: false,
});

const formData = reactive<PrinterForm>({
  status: 1,
  type: 1,
});

const rules = reactive({
  shop_id: [{required: true, message: "请选择所属店铺", trigger: "blur"}],
  title: [{required: true, message: "请输入名称", trigger: "blur"}],
  sn: [{required: true, message: "请输入终端编号", trigger: "blur"}],
  secret: [{required: true, message: "请输入终端识别码", trigger: "blur"}],
  status: [{required: true, message: "请选择状态", trigger: "blur"}],
});

/** 查询 */
function handleQuery() {
  loading.value = true;
  printerList(queryParams)
    .then(({data}) => {
      lists.value = data.items || null;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

/** 打开角色表单弹窗 */
function openDialog(id?: number) {
  dialog.visible = true;
  getSupplierOptions()
    .then((data) => {
      modelFields["shop_id"]["options"] = data.data || [];
    })
    .then(() => {
      if (id) {
        dialog.title = "修改打印机";
        printerDetail(id).then(({data}) => {
          Object.assign(formData, data);
        });
      } else {
        dialog.title = "新增打印机";
      }
    });
}

/** 角色保存提交 */
function handleSubmit() {
  objFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const id = formData.id;
      if (id) {
        updatePrinter(id, formData)
          .then(() => {
            ElMessage.success("修改成功");
            closeDialog();
            resetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        createPrinter(formData)
          .then(() => {
            ElMessage.success("新增成功");
            closeDialog();
            resetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/** 关闭表单弹窗 */
function closeDialog() {
  dialog.visible = false;
  resetForm();
}

/** 重置表单 */
function resetForm() {
  objFormRef.value.resetFields();
  objFormRef.value.clearValidate();

  formData.id = undefined;
  formData.status = 1;
}

/** 删除 */
function handleDelete(id: number) {
  if (!id) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    cancelButtonText: "取消",
    confirmButtonText: "确定",
    type: "warning",
  }).then(() => {
    loading.value = true;
    deletePrinter(id)
      .then(() => {
        ElMessage.success("删除成功");
        resetQuery();
      })
      .finally(() => (loading.value = false));
  });
}

/**
 * 初始化
 * @param id
 */
function handleInitPrinter(id: number) {
  if (!id) {
    ElMessage.warning("数据异常");
    return;
  }

  ElMessageBox.confirm("确认初始化?", "温馨提示", {
    cancelButtonText: "取消",
    confirmButtonText: "确定",
    type: "warning",
  }).then(() => {
    loading.value = true;

    initPrinter(id)
      .then(() => {
        ElMessage.success("初始化成功");
        resetQuery();
      })
      .finally(() => (loading.value = false));
  });
}

/**
 * 初始化
 * @param id
 */
function handleClearPrinter(id: number) {
  if (!id) {
    ElMessage.warning("数据异常");
    return;
  }

  ElMessageBox.confirm("确认清空待打印记录?", "温馨提示", {
    cancelButtonText: "取消",
    confirmButtonText: "确定",
    type: "warning",
  }).then(() => {
    loading.value = true;

    clearPrinter(id)
      .then(() => {
        ElMessage.success("清空成功");
        handleQuery();
      })
      .finally(() => (loading.value = false));
  });
}

onMounted(() => {
  handleQuery();
});
</script>

<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true" class="pull-left">
        <el-form-item prop="keywords" label="">
          <el-input v-model="queryParams.keywords" placeholder="打印机名称" clearable @keyup.enter="handleQuery"/>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <i-ep-search/>
            搜索
          </el-button>
          <el-button @click="resetQuery">
            <i-ep-refresh/>
            重置
          </el-button>
        </el-form-item>

      </el-form>
      <el-button v-hasPerm="['shop:printer:add']" type="primary" @click="openDialog()" class="pull-right">
        <i-ep-plus/>
        新增
      </el-button>
      <div class="clear"></div>
    </div>
    <el-card shadow="never" class="table-container">
      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="lists"
        highlight-current-row
      >
        <el-table-column label="类型" prop="type" width="100">
          <template #default="scope">
            <template v-if="scope.row.type > 0">
              <el-tag :type="scope.row.type == 1 ? 'success' : 'warning'">
                {{ typeOptions[scope.row.type] }}
              </el-tag
              >
            </template>
          </template>
        </el-table-column>
        <el-table-column label="所属店铺" prop="shop_title"/>
        <el-table-column label="打印机名称" prop="title"/>
        <el-table-column label="终端编号" prop="sn"/>
        <el-table-column label="终端识别码" prop="secret"/>
        <el-table-column label="创建时间" prop="create_time"/>
        <el-table-column label="状态" align="center" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status == 1 ? 'success' : 'info'">{{
                statusOptions[scope.row.status]
              }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          width="140"
          class-name="text-center"
        >
          <template #default="scope">
            <el-button
              v-hasPerm="['shop:printer:init']"
              type="primary"
              link
              @click="handleInitPrinter(scope.row.id)"
            >
              <i-ep-CircleCheck class="margin3-r"/>
              初始化
            </el-button>

            <el-button
              v-hasPerm="['shop:printer:clear']"
              type="primary"
              size="small"
              link
              @click="handleClearPrinter(scope.row.id)"
            >
              <i-ep-edit class="margin3-r"/>
              清空待打印
            </el-button>

            <el-button
              v-hasPerm="['shop:printer:edit']"
              type="primary"
              size="small"
              link
              @click="openDialog(scope.row.id)"
            >
              <i-ep-edit class="margin3-r"/>
              编辑
            </el-button>

            <el-button
              v-hasPerm="['shop:printer:delete']"
              type="danger"
              size="small"
              link
              @click="handleDelete(scope.row.id)"
            >
              <i-ep-delete class="margin3-r"/>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>

    <!-- 编辑表单弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="540px"
      @close="closeDialog"
    >
      <el-form
        ref="objFormRef"
        :model="formData"
        :rules="rules"
        label-width="140px"
      >
        <el-form-item
          :label="field.title"
          :prop="fk.toString()"
          v-for="(field, fk) in modelFields"
          :key="fk"
        >
          <el-radio-group v-model="formData[fk]" v-if="field.type == 'radio'">
            <el-radio
              :label="Number(ok)"
              v-for="(op, ok) in field.options"
              :key="ok"
            >{{ op }}
            </el-radio
            >
          </el-radio-group>
          <el-select v-model="formData[fk]" v-else-if="field.type == 'select'">
            <el-option
              :key="Number(ok)"
              :label="op"
              v-for="(op, ok) in field.options"
              :value="Number(ok)"
              v-if="field.isValue"
            />
            <el-option
              :key="Number(op.id)"
              :label="op.title"
              v-for="op in field.options"
              :value="Number(op.id)"
              v-else
            />
          </el-select>
          <el-input
            v-model="formData[fk]"
            :placeholder="'请输入' + field.title"
            v-else
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog" type="default">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
